import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_wan_android/arch/net/http_manager.dart';
import 'package:flutter_wan_android/arch/net/result_data.dart';
import 'package:flutter_wan_android/arch/ui/toast.dart';
import 'package:flutter_wan_android/model/article.dart';
import 'package:flutter_wan_android/res/colors.dart';
import 'package:flutter_wan_android/routes/route_util.dart';
import 'package:flutter_wan_android/routes/routes.dart';
import 'package:flutter_wan_android/res/theme.dart';

import '../r.dart';

class ArticleItem extends StatelessWidget {
  final Article article;
  final Function? onRefresh;

  ArticleItem(this.article, {this.onRefresh});

  @override
  Widget build(BuildContext context) {
    return _articleItem(context);
  }

  /// 文章item
  _articleItem(BuildContext context) {
    // 显示的作者
    var author = article.author;
    if (article.author?.isEmpty == true) {
      author = article.shareUser ?? "";
    }

    // 标题最大行数
    var titleMaxLines = 2;
    if (article.envelopePic?.isNotEmpty == true) titleMaxLines = 1;

    // 是否收藏的图标
    var collectImg;
    if (article.collect == true) {
      collectImg = R.imagesIcCollectFill;
    } else {
      collectImg = R.imagesIcCollectStrock;
    }

    return GestureDetector(
      onTap: () {
        RouteUtil.push(
          context,
          Routes.web,
          params: {"url": article.link, "title": article.title},
        );
      },
      child: Container(
        color: context.wTheme.listItemBg,
        padding: EdgeInsets.all(10),
        child: Column(
          children: [
            // 第一行 作者和时间
            Row(
              children: [
                _articleItemNew(),
                Expanded(
                  child: Text(
                    author ?? "",
                    style: TextStyle(color: WColor.blue1, fontSize: 11),
                  ),
                  flex: 1,
                ),
                Text(
                  article.niceShareDate ?? "",
                  style: TextStyle(color: WColor.gray1, fontSize: 11),
                )
              ],
            ),

            Padding(padding: EdgeInsets.only(top: 8)),

            //中间内容 图片 标题 内容
            Row(
              children: [
                _articleItemImg(),
                Expanded(
                    flex: 1,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: double.infinity,
                          child: Text(
                            article.title ?? "",
                            maxLines: titleMaxLines,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: context.wTheme.text1,
                              fontSize: 16,
                            ),
                          ),
                        ),
                        _articleItemDes()
                      ],
                    ))
              ],
            ),

            // 底部内容
            Padding(padding: EdgeInsets.only(top: 4)),
            Row(
              children: [
                Expanded(
                  flex: 1,
                  child: Text(
                    "${article.superChapterName ?? ""}${article.chapterName}",
                    style: TextStyle(color: WColor.gray1, fontSize: 11),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    _collectArticle();
                  },
                  child: Image.asset(
                    collectImg,
                    width: 20,
                    height: 20,
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 文章列表左侧图片
  _articleItemImg() {
    if (article.envelopePic?.isEmpty == true) return Container();

    return Container(
        padding: EdgeInsets.only(right: 8),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          child: CachedNetworkImage(
            imageUrl: article.envelopePic ?? "",
            width: 120,
            height: 90,
            fit: BoxFit.cover,
          ),
        ));
  }

  /// 文章列表是否是新的标签
  _articleItemNew() {
    if (article.fresh != true) return Container();
    return Image.asset(
      R.imagesIcNew,
      width: 18,
      height: 18,
    );
  }

  /// 文章列表des
  _articleItemDes() {
    if (article.desc?.isEmpty == true) return Container();

    var desc = article.desc
        ?.replaceAll("<ol>", "")
        .replaceAll("</ol>", "")
        .replaceAll("<li>", "")
        .replaceAll("</li>", "")
        .replaceAll("<ul>", "")
        .replaceAll("</ul>", "")
        .replaceAll("<em class='highlight'>", "")
        .replaceAll("</em>", "")
        .replaceAll("<p>", "")
        .replaceAll("</p>", "");

    return Container(
      padding: EdgeInsets.only(top: 5),
      child: Text(
        desc ?? "",
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: WColor.black2,
          fontSize: 14,
        ),
      ),
    );
  }

  /// 收藏文章
  _collectArticle() async {
    if (article.collect == true) {
      // 取消收藏
      _unCollectArticle();
      return;
    }

    var url = "lg/collect/${article.id}/json";
    ResultData result = await HttpManager.instance().post(url);
    if (result.success) {
      ToastUtil.show("收藏成功");
      if (onRefresh != null) onRefresh!();
    } else {
      ToastUtil.show(result.msg);
    }
  }

  /// 取消收藏
  _unCollectArticle() async {
    var url = "";

    var params = {};

    if ((article.originId ?? -100) > -1) {
      // 收藏列表中取消收藏
      url = "lg/uncollect/${article.id}/json";
      params["originId"] = article.originId;
    } else {
      //文章列表中取消收藏
      url = "lg/uncollect_originId/${article.id}/json";
    }

    ResultData result = await HttpManager.instance().post(url, params: params);
    if (result.success) {
      ToastUtil.show("取消收藏成功");
      if (onRefresh != null) onRefresh!();
    } else {
      ToastUtil.show(result.msg);
    }
  }
}

//
// class ArticleItem {
//
//   getItem(BuildContext context, Article article, {Function? onRefresh}) {
//     return _articleItem(context, article, onRefresh);
//   }
//
//   /// 文章item
//   _articleItem(BuildContext context, Article article, Function? onRefresh) {
//     // 显示的作者
//     var author = article.author;
//     if (article.author?.isEmpty == true) {
//       author = article.shareUser ?? "";
//     }
//
//     // 标题最大行数
//     var titleMaxLines = 2;
//     if (article.envelopePic?.isNotEmpty == true) titleMaxLines = 1;
//
//     // 是否收藏的图标
//     var collectImg;
//     if (article.collect == true) {
//       collectImg = R.imagesIcCollectFill;
//     } else {
//       collectImg = R.imagesIcCollectStrock;
//     }
//
//     return GestureDetector(
//       onTap: () {
//         RouteUtil.push(
//           context,
//           Routes.web,
//           params: {"url": article.link, "title": article.title},
//         );
//       },
//       child: Container(
//         padding: EdgeInsets.all(10),
//         child: Column(
//           children: [
//             // 第一行 作者和时间
//             Row(
//               children: [
//                 _articleItemNew(article),
//                 Expanded(
//                   child: Text(
//                     author ?? "",
//                     style: TextStyle(color: WColor.blue1, fontSize: 11),
//                   ),
//                   flex: 1,
//                 ),
//                 Text(
//                   article.niceShareDate ?? "",
//                   style: TextStyle(color: WColor.gray1, fontSize: 11),
//                 )
//               ],
//             ),
//
//             Padding(padding: EdgeInsets.only(top: 8)),
//
//             //中间内容 图片 标题 内容
//             Row(
//               children: [
//                 _articleItemImg(article),
//                 Expanded(
//                     flex: 1,
//                     child: Column(
//                       crossAxisAlignment: CrossAxisAlignment.start,
//                       children: [
//                         Container(
//                           width: double.infinity,
//                           child: Text(
//                             article.title ?? "",
//                             maxLines: titleMaxLines,
//                             overflow: TextOverflow.ellipsis,
//                             style: TextStyle(
//                               color: WColor.black1,
//                               fontSize: 16,
//                             ),
//                           ),
//                         ),
//                         _articleItemDes(article)
//                       ],
//                     ))
//               ],
//             ),
//
//             // 底部内容
//             Padding(padding: EdgeInsets.only(top: 4)),
//             Row(
//               children: [
//                 Expanded(
//                   flex: 1,
//                   child: Text(
//                     "${article.superChapterName ?? ""}${article.chapterName}",
//                     style: TextStyle(color: WColor.gray1, fontSize: 11),
//                   ),
//                 ),
//                 GestureDetector(
//                   onTap: () {
//                     _collectArticle(article, onRefresh);
//                   },
//                   child: Image.asset(
//                     collectImg,
//                     width: 20,
//                     height: 20,
//                   ),
//                 )
//               ],
//             ),
//           ],
//         ),
//       ),
//     );
//   }
//
//
// }
//
// /// 文章列表左侧图片
// _articleItemImg(Article article) {
//   if (article.envelopePic?.isEmpty == true) return Container();
//
//   return Container(
//       padding: EdgeInsets.only(right: 8),
//       child: ClipRRect(
//         borderRadius: BorderRadius.all(Radius.circular(8)),
//         child: CachedNetworkImage(
//           imageUrl: article.envelopePic ?? "",
//           width: 120,
//           height: 90,
//           fit: BoxFit.cover,
//         ),
//       ));
// }
//
// /// 文章列表是否是新的标签
// _articleItemNew(Article article) {
//   if (article.fresh != true) return Container();
//   return Image.asset(
//     R.imagesIcNew,
//     width: 18,
//     height: 18,
//   );
// }
//
// /// 文章列表des
// _articleItemDes(Article article) {
//   if (article.desc?.isEmpty == true) return Container();
//
//   var desc = article.desc
//       ?.replaceAll("<ol>", "")
//       .replaceAll("</ol>", "")
//       .replaceAll("<li>", "")
//       .replaceAll("</li>", "")
//       .replaceAll("<ul>", "")
//       .replaceAll("</ul>", "")
//       .replaceAll("<p>", "")
//       .replaceAll("</p>", "");
//
//   return Container(
//     padding: EdgeInsets.only(top: 5),
//     child: Text(
//       desc ?? "",
//       maxLines: 3,
//       overflow: TextOverflow.ellipsis,
//       style: TextStyle(
//         color: WColor.black2,
//         fontSize: 14,
//       ),
//     ),
//   );
// }
//
// /// 收藏文章
// _collectArticle(Article article, Function? onRefresh) async {
//
//   if(article.collect == true){ // 取消收藏
//     _unCollectArticle(article, onRefresh);
//     return;
//   }
//
//   var url = "lg/collect/${article.id}/json";
//   ResultData result = await HttpManager.instance().post(url);
//   if (result.success) {
//     ToastUtil.show("收藏成功");
//     if(onRefresh != null)onRefresh();
//   } else {
//     ToastUtil.show(result.msg);
//   }
// }
//
// /// 取消收藏
// _unCollectArticle(Article article, Function? onRefresh) async{
//
//   var url = "";
//
//   var params = {};
//
//   if((article.originId ?? -100) > -1){ // 收藏列表中取消收藏
//     url = "lg/uncollect/${article.id}/json";
//     params["originId"] = article.originId;
//   }else{ //文章列表中取消收藏
//     url = "lg/uncollect_originId/${article.id}/json";
//   }
//
//   ResultData result = await HttpManager.instance().post(url, params: params);
//   if (result.success) {
//     ToastUtil.show("取消收藏成功");
//     if(onRefresh != null)onRefresh();
//   } else {
//     ToastUtil.show(result.msg);
//   }
// }
